package com.huan.springcloud.spring;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * <pre>
 * 打印出每个bean的耗时，需要打印出层级关系
 * A(6s)
 *      B(3s)
 *          D(1s)
 *      E(1s)
 * </pre>
 *
 * @author huan.fu
 * @date 2022/7/20 - 10:49
 */
@Component
@Slf4j
public class PrintBeanCostTimeApplicationRunner implements ApplicationRunner {

    @Override
    public void run(ApplicationArguments args) throws Exception {
        List<BeanLoadTimeCostBeanFactory.BeanCost> beanCosts = BeanLoadTimeCostBeanFactory.beanCosts;
        for (int i = beanCosts.size() - 1; i >= 0; i--) {
            BeanLoadTimeCostBeanFactory.BeanCost beanCost = beanCosts.get(i);
            String beanName = beanCost.getBeanName();
            long cost = beanCost.getEnd() - beanCost.getStart();
            for (int j = 0; j < beanCost.getLevel(); j++) {
                System.out.print("\t");
            }
            System.out.println("beanName:[" + beanName + "] cost:[" + cost + "]ms");
        }
    }
}
